<?php

namespace Project\Model;

use Zend\Db\TableGateway\TableGateway;

class TaskTable
{
	protected $tableGateway;

	public function __construct(TableGateway $tableGateway)
	{
		$this->tableGateway = $tableGateway;
	}

	public function fetchAll()
	{
		$resultSet = $this->tableGateway->select();
		return $resultSet;
	}

	public function getTask($id)
	{
		$id  = (int) $id;
		$rowset = $this->tableGateway->select(array('id' => $id));
		$row = $rowset->current();
		if (!$row) {
			throw new \Exception("Could not find row $id");
		}
		return $row;
	}

	public function saveTask(Task $task)
	{
		$data = array(
				'id' => $task->id,
				'completeddatetime' => $task->completeddatetime,
				'completed'  => $task->completed,
				'duedatetime'  => $task->duedatetime,
				'description'  => $task->description,
				'name'  => $task->name,
				'status'  => $task->status,
				'activity_id'  => $task->activity_id,
				'requestedbyuser__user_id'  => $task->requestedbyuser__user_id,
				'project_id'  => $task->project_id,
				
		);

		$id = (int)$task->id;
		if ($id == 0) {
			$this->tableGateway->insert($data);
		} else {
			if ($this->getTask($id)) {
				$this->tableGateway->update($data, array('id' => $id));
			} else {
				throw new \Exception('Form id does not exist');
			}
		}
	}

	public function deleteTask($id)
	{
		$this->tableGateway->delete(array('id' => $id));
	}
}